package day11;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

//a.模拟火车站售票窗口，要求：票池共100张票，3个售票窗口同时卖票
//,售票过程需显示"窗口X卖出第Y张票",使用Lock锁保证票数正确
//当票卖完时所有线程终止
public
class TestLock {
    static ReentrantLock lock=new ReentrantLock();
    static int sum=100;//票池
    static int num=0;//卖出的票
    public static void buy(){

        while (sum>0){
            //lock.tryLock(1000);//等待1000毫秒  成功返回true  失败返回false
            //lock.tryLock(时间,时间单位) //等待指定时间，过后自动释放锁
            try {
            if (lock.tryLock(3, TimeUnit.SECONDS)) {//尝试获取锁   成功返回true  失败返回false
                try {

                    if (sum > 0) {
                        num++;
                        System.out.println(Thread.currentThread().getName() + "卖出第" + num + "张票");
                        sum--;
                        Thread.sleep(100);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }else {
                System.out.println(Thread.currentThread().getName() + "没有获取到锁，等待中");
            }
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }

    }
    public static
    void main(String[] args) {
        new Thread(()->{
            buy();
        },"窗口1").start();
        new Thread(()->{
            buy();
        },"窗口2").start();
        new Thread(()->{
            buy();
        },"窗口3").start();
    }
}
